package com.boilermaker.lotterysystem.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MailUtil {

    @Value(value = "${spring.mail.username}")
    private String from; // 发件地址

    @Autowired
    private JavaMailSender mailSender;

    /**
     * 发邮件
     *
     * @param to:      收件地址
     * @param subject： 邮件标题
     * @param context： 邮件正文
     * @return
     */
    public Boolean sendSampleMail(String to, String subject, String context) {

        SimpleMailMessage mail = new SimpleMailMessage();
        mail.setFrom(from);
        mail.setTo(to);
        mail.setSubject(subject);
        mail.setText(context);

        try {
            mailSender.send(mail);
        } catch (Exception e) {
            log.error("向 {} 发送邮件失败！", to, e);
            return false;
        }

        return true;
    }
}
